package com.juphoon.oauth.browser.filter;

import com.juphoon.oauth.browser.handler.AuthFailHandler;
import lombok.AllArgsConstructor;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@AllArgsConstructor
public class ImageCodeFilter extends OncePerRequestFilter {

    private AuthFailHandler authFailHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if (request.getRequestURI().equals("/auth")) {
            HttpSession session = request.getSession();
            String sessionCode = (String) session.getAttribute("code");
            session.removeAttribute("code");
            String code = request.getParameter("code");
            try {
                vaildataImage(sessionCode, code);
            } catch (RuntimeException ex) {
                authFailHandler.onAuthenticationFailure(request, response, new AuthenticationException(ex.getMessage()) {
                });
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private void vaildataImage(String sessionCode, String code) throws AuthenticationException {
        if (StringUtils.isEmpty(code)) {
            throw new RuntimeException("验证码为空");
        }
        if (StringUtils.isEmpty(sessionCode)) {
            throw new RuntimeException("验证码过期");
        }
        if (!sessionCode.equals(code)) {
            throw new RuntimeException("验证码不正确");
        }
    }



}
